package cn.sima.plantmessage.user;

import java.io.File;
import java.io.FileNotFoundException;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;

import cn.sima.plantmessage.Conf;
import cn.sima.plantmessage.MainActivity;
import cn.sima.plantmessage.R;
import cn.sima.plantmessage.cache.ACache;
import net.tsz.afinal.FinalDb;
import cn.sima.plantmessage.dialog.DialogUtils.OnConfirmListener;
import cn.sima.plantmessage.dialog.DialogUtils;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class UploadUserHeadActivity extends Activity implements OnClickListener {
	private Button selectImage, uploadImage;
	private ImageView imageView;
	private String picPath = null;
	private ACache userCache;

	private String uuid="";
	@SuppressLint("NewApi")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        
        setContentView(R.layout.fragment_uploaduserheadpic);
 
    	ActionBar ab = getActionBar();
		setTitle("更新头像");
		ab.setDisplayHomeAsUpEnabled(true);
		ab.setHomeButtonEnabled(true);

        
        selectImage = (Button) this.findViewById(R.id.selectImage);
        uploadImage = (Button) this.findViewById(R.id.uploadImage);
        selectImage.setOnClickListener(this);
        uploadImage.setOnClickListener(this);
 
        imageView = (ImageView) this.findViewById(R.id.imageView);
        
        userCache = ACache.get(this.getApplicationContext(), "userCache");
		String userinfo = userCache.getAsString("user");
		JsonObject userinfoJson =  new JsonParser().parse(userinfo).getAsJsonObject();
		uuid = userinfoJson.get("uuid").getAsString();
		
		Log.e("uploadUserAvatar uuid",uuid);
 
    }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {

			// 关闭Activity
			UploadUserHeadActivity.this.finish();
			// overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
			overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);

			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.selectImage:
			/***
			 * 这个是调用android内置的intent，来过滤图片文件 ，同时也可以过滤其他的
			 */
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(intent, 1);

			break;
		case R.id.uploadImage:
			if (picPath == null) {
				Toast.makeText(this, "请选择图片！", Toast.LENGTH_SHORT).show();
			} else {
				final File file = new File(picPath);

				if (file != null) {
//					String request = UploadUtil.uploadFile(file, requestURL);
//					uploadImage.setText(request);
					
					
					Ion.with(this)
					.load(Conf.BASE_URL+"/user/uploadUserAvatar")
					.setMultipartParameter("uuid", uuid)
					.setMultipartFile("pic", file)
					.asJsonObject()
					.setCallback(new FutureCallback<JsonObject>() {
					   @Override
					    public void onCompleted(Exception e, JsonObject result) {
						   Log.e("uploadUserAvatar =result",result.toString());
						   if(result.get("success").getAsBoolean()){
							   String user =  result.get("user").toString();
							   Toast.makeText(getApplicationContext(), "上传成功",
										Toast.LENGTH_SHORT).show();
							   userCache.remove("user");
							   userCache.put("user", user);
							   //通过Intent对象返回结果，setResult方法，
							   Intent it = new Intent();
							   setResult(RESULT_OK,it);
							   finish();//结束当前的Activity的生命周期。
							   
//							   Intent intent = new Intent();
//							   intent.putExtra("LoginParam", param);
//							   //通过Intent对象返回结果，setResult方法，
//							   setResult(RESULT_OK, intent);
//							   finish();//结束当前的Activity的生命周期。
						   }else{
							   Toast.makeText(getApplicationContext(), "上传失败",
										Toast.LENGTH_SHORT).show();
						   }
						   
					   }
					});
				}
			}
			break;
		default:
			break;
		}

	}
	
	
	
	 @Override
	 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		 
		 
		 
	        if (resultCode == Activity.RESULT_OK) {
	            /**
	             * 当选择的图片不为空的话，在获取到图片的途径
	             */
	            Uri uri = data.getData();
	            Log.e("uri", "uri = " + uri);
	            try {
	                String[] pojo = { MediaStore.Images.Media.DATA };
	 
	                Cursor cursor = managedQuery(uri, pojo, null, null, null);
	                if (cursor != null) {
	                    ContentResolver cr = this.getContentResolver();
	                    int colunm_index = cursor
	                            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	                    cursor.moveToFirst();
	                    String path = cursor.getString(colunm_index);
	                    /***
	                     * 这里加这样一个判断主要是为了第三方的软件选择，比如：使用第三方的文件管理器的话，你选择的文件就不一定是图片了，
	                     * 这样的话，我们判断文件的后缀名 如果是图片格式的话，那么才可以
	                     */
	                    if (path.endsWith("jpg") || path.endsWith("png")) {
	                        picPath = path;
	                        Bitmap bitmap = BitmapFactory.decodeStream(cr
	                                .openInputStream(uri));
	                        imageView.setImageBitmap(bitmap);
	                        userCache.put("user_head_pic", bitmap);
	                    } else {
	                        alert();
	                    }
	                } else {
	                    alert();
	                }
	 
	            } catch (Exception e) {
	            }
	        }
	 
	        super.onActivityResult(requestCode, resultCode, data);
	    }
	 
	    private void alert() {
	        Dialog dialog = new AlertDialog.Builder(this).setTitle("提示")
	                .setMessage("您选择的不是有效的图片")
	                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int which) {
	                        picPath = null;
	                    }
	                }).create();
	        dialog.show();
	    }

}
